import React from "react";
import routeWithUserSession from "@/components/ApplicationArea/routeWithUserSession";
import PageHeader from "@/components/PageHeader";
import { ControllerType } from "@/components/items-list/ItemsList";
import { BrowserRouter as Router,Link } from 'react-router-dom';//
import "./Contract.css";
import {Layout, Button, Col, Divider, Form, Input, Row, Table, ConfigProvider, Modal, Tree} from "antd/lib";
import zhCN from 'antd/es/locale/zh_CN';
import ContractApply from "@/services/contractapply";
//import { createHashHistory } from 'history';
import {createBrowserHistory} from 'history'
import notification from "@/services/notification";
import {get} from "lodash";
import { currentUser } from "@/services/auth";
import Enums from "@/services/enums";
import routes from "@/services/routes";
import {WarningOutlined,SecurityScanTwoTone,DownOutlined} from "@ant-design/icons";
const customHistory = createBrowserHistory();
//const HashHistory = createHashHistory();
//const history = useHistory();
const {Sider } = Layout;
const { confirm } = Modal;
const getRowClassName = (record, index) => {
  let className = '';
  if (index % 2 === 0) className = "oddRow";
  return className
}
class ApplyList extends React.Component {
  state = {
    page: 1,
    pagesize: 10,
    total:10,
    loading: false,
    code: '',
    name: '',
    party_a: '',
    party_b: '',
    data: [],
    gData: [],
    selectedKeys: '',
    selectedTitle: '',
  };
  static propTypes = {
    controller: ControllerType.isRequired,
  };
    items=[{
      name:"cght",
      slug:"imgs",
      tags:"tags",
      is_draft:"df",
      is_archived:true
    }];
  componentWillMount() {
    this.loadData();
    let param={
      page: this.state.page,
      pagesize: this.state.pagesize,
      code: this.state.code,
      name: this.state.name,
      party_a: this.state.party_a,
      type: this.state.selectedKeys,
      userid: currentUser.id,
    }
    this.fetch(param);
  }
  fetch = (params = {}) => {
    this.setState({ loading: true });
     ContractApply.getlist(params).then(data => {
        this.setState({
            loading: false,
            data:data.data,
            page: params.page,
            pagesize: params.pagesize,
            total: data.total,
        });
    });
  };
  handlesel = () => {
    let param={
      page: 1,
      pagesize: this.state.pagesize,
      code: this.state.code,
      name: this.state.name,
      party_a: this.state.party_a,
      type: this.state.selectedKeys,
      userid: currentUser.id,
    }
    this.fetch(param);
  };
   handleTableChange = (pagination, filters, sorter) => {
    let field=sorter.field;
    let order=0;
    if(sorter.order==="descend"){
      order=1;
    }
    let param={
      field: field,
      order: order,
      page: pagination.current,
      pagesize: pagination.pageSize,
      code: this.state.code,
      name: this.state.name,
      party_a: this.state.party_a,
      type: this.state.selectedKeys,
      userid: currentUser.id,
    }
    this.fetch(param);
  };
  // handleUpdate = record => {
  //   this.props.history.push("/contract/apply/new/19")
  //   // ContractNew.show()
  //   // .onClose((result = {}) => {
  //   //   }).onDismiss(() => {
  //   //   });
  // };
  // handleUpdate = record => {
  //  // history.push("/contract/apply/new/19");
  //   this.props.history.push(`/contract/apply/new/19`);
  //   //customHistory.push(`/contract/apply/new/19`);
  //  //  customHistory.push({
  //  //    pathname: '/contracts/finish',
  //  //    // pathname: '/contract/apply/new/19',
  //  //    query: {
  //  //      id: record.id
  //  //    },
  //  //  })
  // }
  handlecontractadd = record => {
    if(record.status !==2)
    {
       notification.error("只有在审批状态可以生成合同，生成合同失败！");
       return;
    }
    confirm({
      title: '确定生成正式合同?',
      icon: <WarningOutlined />,
      content: record.name,
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      onOk: () => {
        let param={
         sourcebill:"contractapply",
         sourcebillid:record.id,
         bill:"contracts",
         userid:currentUser.id,
         typeid: 0,
        }
        ContractApply.getpushbill(param).then(data => {
          if(data[0].flag===0) {
            notification.success("生成正式合同成功,编号："+data[0].code);
            let param = {
              page: 1,
              pagesize: this.state.pagesize,
              code: this.state.code,
              name: this.state.name,
              party_a: this.state.party_a,
              type: this.state.selectedKeys,
              userid: currentUser.id,
            }
            this.fetch(param);
          }else{
            notification.error("生成正式合同失败.");
          }
        }).catch(error => {
          notification.error(get(error, "response.data.message", "生成正式合同失败."));
        });
      },
    });
  };
  handleDelete = record => {
    if(record.status !==0)
    {
       notification.error("只有在草稿状态可以删除，删除失败！");
       return;
    }
    confirm({
      title: '确定删除合同申请单?',
      icon: <WarningOutlined />,
      content: record.name,
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      onOk: () => {
        ContractApply.delete(record).then(()=>{
          notification.success("合同申请单删除成功.");
          let param={
            page: 1,
            pagesize: this.state.pagesize,
            code: this.state.code,
            name: this.state.name,
            party_a: this.state.party_a,
            type: this.state.selectedKeys,
            userid: currentUser.id,
          }
          this.fetch(param);
        }).catch(error => {
          notification.error(get(error, "response.data.message", "删除失败."));
        });
      },
    });
  };
  loadData=()=> {
    Enums.items("contract_enum").then(data => {
      const loop = (das, index) => {
        let items=[];
        das.forEach((item) => {
          item.icon= <SecurityScanTwoTone />;
          if (item.children) {
            item.children= loop(item.children, index+1);
          }
          items.push(item);
        });
        return items;
      };
      let datas=loop(data,0);
      this.setState({
        loading: false,
        gData: datas,
        selectedKeys: '',
        selectedTitle: '',
      });
    });
  }
  onSelect = (selectedKeys, e) => {
          let param={
            page: 1,
            pagesize: this.state.pagesize,
            code: this.state.code,
            name: this.state.name,
            party_a: this.state.party_a,
            type: selectedKeys[0],
            userid: currentUser.id,
          }
          this.fetch(param);
    // this.setState({
    //   selectedKeys: selectedKeys[0],
    //   selectedTitle: e.node.props.title,
    // });
};
onDragEnter = info => {
    console.log(info);
  };
  render() {
    // const { currentPage } = this.state;
      const paginationProps = {
            showSizeChanger: true,
            // showQuickJumper: true,
            total: this.state.total, // 数据总数
            pageSize: parseInt(this.state.pagesize), // 每页条数
            current: parseInt(this.state.page), // 当前页码
            pageSizeOptions: ["10", "20", "30","100"],
            showTotal: ((total) => {
              return `共 ${total} 条`;
            }),
          };
        const listcolumns = [
      {
        title: '合同编码',
        key: 'code',
        dataIndex: 'code',
        render: (text, record) => (
// <Link to="/contract/new">
// <Button className="e-button" type="primary">{text}</Button>
// </Link>
//          <a href='/contract/apply/new/${item.filmId}'>{text}</a>
          <Router  history={customHistory}>
            <Link to={`/contract/apply/new/${record.id}`}>{text}</Link>
           </Router>
//           <a className="clickable" onClick={() => this.handleUpdate(record)}>{text}</a>
      // <Router  history={customHistory}>
      //   <Link to={{
      //           pathname: '/contract/apply/new',
      //           state: { id: record.id}
      //       }} >
      //      {text}
      //   </Link>
      //   </Router>
        ),
        sorter: (a, b) => a.code > b.code ? 1 : -1
      },
      {
        title: '合同名称',
        dataIndex: 'name',
        key: 'name',
        sorter: (a, b) => a.name > b.name ? 1 : -1
      },
      {
        title: '合同单位',
        dataIndex: 'partyaname',
        key: 'partyaname',
        sorter: (a, b) => a.partyaname > b.partyaname ? 1 : -1
      },
      {
        title: '合同分类',
        dataIndex: 'typename',
        key: 'typename',
        sorter: (a, b) => a.typename > b.typename ? 1 : -1
      },
      {
        title: '合同金额',
        dataIndex: 'amount',
        key: 'amount',
        sorter: (a, b) => a.amount > b.amount ? 1 : -1
      },
      {
        title: '状态',
        key: 'action',
        render: (record) => (
          <span>
           {!record.blniscontract && (<a className="clickable" onClick={() => this.handlecontractadd(record)}>生成合同</a>)}
           {record.blniscontract && (
             <Router  history={customHistory}>
              <Link to={`/contract/new/${record.contractsid}`}>查看合同</Link>
             </Router>
           )}
            <Divider type="vertical" />
             <a className="clickable" onClick={() => this.handleDelete(record)}>删除</a>
          </span>
        ),
      },
    ];
    return (
  <ConfigProvider locale={zhCN}>
    {/*<div className="page-dashboard-list"> className="container"*/}
    <div  style={{width:"400px",height:"60px"}}>
        <div style={{width:"20px",height:"50px", float: "left"}}>
        </div>
          <div style={{width:"50px",height:"50px", float: "left"}}>
          <img src="/static/images/contractapply.png"/>
        </div>
          <div style={{width:"320px",height:"30px",float:"left"}}>
          {/* <PageHeader title="合同列表" style={{margin:"7px",padding:"0"}}/>  */}
          <h3 style={{margin:"7px",padding:"0"}}>合同申请单列表</h3>
        </div>
      </div>
      {/* <div className="container">
         <Row >
            <Col align="right" span={1}>
              <img src="/static/images/contractapply.png"/>
            </Col>
            <Col  align="left" span={20}>
              <PageHeader title="合同申请单列表" />
            </Col>
          </Row>
      </div> */}
      <Layout>
          {/* <Layout>
            <Sider width={300} style={{ background: '#fff' }}>
              <Tree
                className="draggable-tree"
                draggable
                blockNode
                showIcon
                // showLine
                switcherIcon={<DownOutlined />}
                defaultExpandAll
                onDragEnter={this.onDragEnter}
                onSelect={this.onSelect}
                treeData={this.state.gData}
              />
            </Sider> */}
        <Layout style={{ padding: '0 24px 24px' }}>
         <Form layout="horizontal" {...{labelCol: { span: 4 }, wrapperCol: { span: 14 },} }>
          <Row>
				  <Col span={10}>
            <Form.Item style={{ marginBottom: 5 }} label="合同编码">
              <Input
                value={this.state.code}
                onChange={e => this.setState({code:e.target.value})}
                placeholder="合同编码"
                autoFocus
              />
						</Form.Item>
				  </Col>
				  <Col span={10}>
            <Form.Item style={{ marginBottom: 5 }} label="合同名称">
              <Input
                value={this.state.name}
                onChange={e => this.setState({name:e.target.value})}
                placeholder="合同名称"
              />
						</Form.Item>
				  </Col>
          </Row>
          <Row>
				  <Col span={10}>
            <Form.Item style={{ marginBottom: 5 }} label="合同单位">
              <Input
                value={this.state.party_a}
                onChange={e => this.setState({party_a:e.target.value})}
                placeholder="合同单位"
              />
            </Form.Item>
           </Col>
				  {/*<Col span={10}>*/}
          {/*  <Form.Item style={{ marginBottom: 5 }} label="乙方">*/}
          {/*    <Input*/}
          {/*      value={this.state.party_b}*/}
          {/*      onChange={e => this.setState({party_b:e.target.value})}*/}
          {/*      placeholder="乙方"*/}
          {/*    />*/}
          {/*  </Form.Item>*/}
				  {/*</Col>*/}
          </Row>
          <Row>
				  <Col span={10}>
          <Button type="primary" onClick={() => this.handlesel()} >
            <i className="fa fa-search m-r-5" />
            查询
          </Button>
				  </Col>
          </Row>
         </Form>
          <div>
              <Table rowKey='id'
                    rowClassName={(record, index) => getRowClassName(record, index)}
                    columns={listcolumns}
                    scroll={{x:'max-content'}}
                     dataSource={this.state.data}
                     pagination={paginationProps}
                     loading={this.state.loading}
                     onChange={this.handleTableChange}
              />
         </div>
        </Layout>
        {/* </Layout> */}
       </Layout>
    {/*</div>*/}
  </ConfigProvider>
    );
  }
}

// const ApplyListPage = itemsList(
//   ApplyList,
//   // () =>
//   //   new ResourceItemsSource({
//   //     getResource({ params: { currentPage } }) {
//   //       return {
//   //         all: Dashboard.query.bind(Dashboard),
//   //         favorites: Dashboard.favorites.bind(Dashboard),
//   //       }[currentPage];
//   //     },
//   //     getItemProcessor() {
//   //       return item => new Dashboard(item);
//   //     },
//   //   }),
//   // () => new UrlStateStorage({ orderByField: "created_at", orderByReverse: true })
// );
routes.register(
  "Contractapply.List",
  routeWithUserSession({
    path: "/contracts/apply",
    title: "提交的合同申请单",
    render: pageProps => <ApplyList {...pageProps}/>,
  })
);
routes.register(
  "Contractapply.List1",
  routeWithUserSession({
    path: "/contracts/apply/approve",
    title: "待审批的合同申请单",
    render: pageProps => <ApplyList {...pageProps}/>,
  })
);
// export default [
//   routeWithUserSession({
//     path: "/contracts/apply",
//     title: "我提交的合同申请单",
//     render: pageProps => <ApplyList {...pageProps} />,
//   }),
//   routeWithUserSession({
//     path: "/contracts/apply/approve",
//     title: "待我审批的合同申请单",
//     render: pageProps => <ApplyList {...pageProps} />,
//   }),
// ];
